<template>
  <div class="weather-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input 
        v-model="cityName" 
        placeholder="请输入城市名称" 
        class="search-input">
      </el-input>
      <el-button type="primary" @click="searchWeather">搜索</el-button>
    </div>

    <!-- 当前天气展示区域 -->
    <div class="current-weather" v-if="nowWeatherData != null || nowWeatherData != undefined || nowWeatherData != ''">
      <div class="current-temp">
        <span class="temp-celsius">温度{{ nowWeatherData.temp }}°C</span>
        <span class="temp-celsius">体感温度{{ nowWeatherData.feelsLike }}°C</span>
      </div>
      <div class="current-info">
        <div class="weather-desc">
          {{ nowWeatherData.text }}
          <i style="font-size: 50px;" :class="`qi-`+nowWeatherData.icon"></i>
        </div>
        <div class="weather-details">
          <span>风向: {{ nowWeatherData.windDir }}</span>
          <span>湿度: {{nowWeatherData.humidity}}%</span>
        </div>
        <div class="weather-other">
          <span>能见度: {{ nowWeatherData.vis }}km</span>
        </div>
        <div class="location-time">
          {{ cityName }} - {{ getCurrentTime() }}
        </div>
      </div>
    </div>

    <!-- 小时预报 -->
    <div class="hourly-forecast" v-if="sixHourWeatherData.length > 0">
      <div class="forecast-hours">
        <div class="hour-item" v-for="(item, index) in sixHourWeatherData" :key="index">
          <div class="hour-time">{{ item.fxTime.substring(11,16) }}</div>
          <div class="hour-icon">
            <i :class="`qi-${item.icon}`"></i>
          </div>
          <div class="hour-temp">{{ item.temp }}°C</div>
          <div class="hour-text">{{ item.text }}</div>
          <div class="hour-wind">{{ item.windDir }}</div>
        </div>
      </div>
    </div>

    <!-- 未来天气预报 -->
    <div class="daily-forecast" v-if="weatherData.length > 0">
      <div class="forecast-day" v-for="(item, index) in weatherData" :key="index">
        <div class="day">{{ item.fxDate }}</div>
        <div class="weather-icon">
          <el-text style="font-size: 15px;padding-right: 5px;" class="mx-1">{{ item.textNight }}</el-text>
          <i style="font-size: 30px;" :class="`qi-`+item.iconDay"></i>
        </div>
        <div class="weather-text">{{ item.textDay }}</div>
        <div class="temp-range">
          <span class="high" style="color: red;">{{ item.tempMax }}°</span>
          ~
          <span class="low" style="color: cornflowerblue;">{{ item.tempMin }}°</span>
        </div>
      </div>
    </div>

    <!-- 无数据提示 -->
    <el-empty 
      v-else 
      description="请输入城市名称查询天气" 
      :image-size="200">
    </el-empty>
  </div>
</template>
  
<script>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios';

export default {
  setup() {
    const cityName = ref('武汉')

    const nowWeatherData = ref({})

    let flushNowWeatherData;

    const weatherData = ref([])

    const sixHourWeatherData = ref([
      {
        "fxTime": "2025-01-18T21:00+08:00",
        "temp": "4",
        "icon": "150",
        "text": "晴",
        "wind360": "195",
        "windDir": "南风",
        "windScale": "1-3",
        "windSpeed": "5",
        "humidity": "43",
        "pop": "7",
        "precip": "0.0",
        "pressure": "1016",
        "cloud": "24",
        "dew": "-3"
      }
    ])

    const getSixHourWeatherData = () => {
      if (!cityName.value) {
        return
      }
      axios.get('api/weather/hour?cityName='+cityName.value)
      .then(res => {
        if(res.data.code === 200){
          sixHourWeatherData.value = res.data.data;
        }else{
          ElMessage.error(res.data.message)
        }
      }).catch(err => {
        ElMessage.error('数据加载失败')
      })
    }

    const getNowWeatherData = () => {
      axios.get('api/weather/now?cityName='+cityName.value)
      .then(res => {
        if(res.data.code === 200){
          nowWeatherData.value = res.data.data.now;
        }else{
          ElMessage.error(res.data.message)
        }
      }).catch(err => {
        ElMessage.error('数据加载失败')
      })
    }

    const getCurrentTime = () => {
      return new Date().toLocaleTimeString('en-US', { 
        hour: 'numeric',
        minute: 'numeric',
        hour12: true
      })
    }

    const formatDay = (date) => {
      return new Date(date).toLocaleDateString('en-US', { 
        weekday: 'short',
        day: 'numeric'
      })
    }

    const searchWeather = () => {
      if (!cityName.value) {
        ElMessage.warning('请输入城市名称')
        return
      }
      axios.get('api/weather/sevenDay?cityName='+cityName.value)
      .then(res => {
        if(res.data.code === 200){
          const data = res.data.data;
          weatherData.value = data.daily;
          getSixHourWeatherData()
          ElMessage.success(`已加载${cityName.value}的天气信息`)
        }else{
          ElMessage.error(res.data.message)
        }
      }).catch(err => {
        ElMessage.error('数据加载失败')
      })
    }

    onMounted(() => {
      searchWeather()
      getNowWeatherData()
      getSixHourWeatherData()
      // 每5分钟刷新一次当前天气数据
      flushNowWeatherData = setInterval(getNowWeatherData, 5 * 60 * 1000);
    })

    onBeforeUnmount(() => {
      clearInterval(flushNowWeatherData);
    });

    return {
      cityName,
      weatherData,
      searchWeather,
      getCurrentTime,
      formatDay,
      nowWeatherData,
      getNowWeatherData,
      sixHourWeatherData,
      getSixHourWeatherData
    }
  }
}
</script>

<style scoped>
    .hourly-forecast {
      margin: 20px 0;
      padding: 15px;
      background: rgba(255, 255, 255, 0.8);
      border-radius: 12px;
    }
    .forecast-hours {
      display: flex;
      justify-content: space-between;
      overflow-x: hidden;
    }
    .hour-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 0 15px;
      min-width: 100px;
    }
    .hour-time {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 8px;
    }
    .hour-icon i {
      font-size: 30px;
      margin: 8px 0;
    }
    .hour-temp {
      font-size: 18px;
      font-weight: bold;
      color: #f56c6c;
    }
    .hour-text {
      font-size: 14px;
      color: #606266;
      margin: 4px 0;
    }
    .hour-wind {
      font-size: 12px;
      color: #909399;
    }
    </style>

<style scoped>
.weather-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  background-color: #f0f2f5;
}

.search-area {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.search-input {
  width: 300px;
  margin-right: 10px;
}

.current-weather {
  background: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);
  color: white;
  padding: 30px;
  border-radius: 15px;
  margin-bottom: 20px;
}

.current-temp {
  font-size: 48px;
  margin-bottom: 20px;
}

.temp-unit {
  font-size: 24px;
  margin-left: 5px;
}

.temp-celsius {
  font-size: 18px;
  margin-left: 10px;
  opacity: 0.8;
}

.current-info {
  font-size: 18px;
}

.weather-details {
  margin: 10px 0;
  font-size: 14px;
}

.weather-details span {
  margin-right: 20px;
}

.hourly-forecast {
  background: white;
  padding: 20px;
  border-radius: 15px;
  margin-bottom: 20px;
}

.time-slots {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.daily-forecast {
  background: white;
  padding: 20px;
  border-radius: 15px;
}

.forecast-day {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.temp-range {
  width: 80px;
  text-align: right;
}

.temp-range .high {
  color: #f56c6c;
}

.weather-container {
  border-radius: 5%;
  margin-top: 20px;
  background-color: dodgerblue;
}

</style>

